﻿using Digitalmes.Common.Exceptions;
using Digitalmes.Common.Result;

namespace Digitalmes.ApiService.Filters;

/// <summary>
/// 全局异常处理
/// </summary>
public sealed class GlobalExceptionFilter : IAsyncExceptionFilter
{
    private readonly ILogger _logger;

    public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
    {
        _logger = logger;
    }

    public Task OnExceptionAsync(ExceptionContext context)
    {
        if (context.ExceptionHandled) 
            return Task.CompletedTask;

        var result = new ApiResult<string?>
        {
            Code = (int)HttpStatusCode.InternalServerError,
            Message = context.Exception.Message,
        };

        if (context.Exception is FriendlyException ex)
        {
            result.Code = (int)HttpStatusCode.Found;
            result.Message = $"[{ex.ErrorCode}] {ex.ErrorMessage}";
        }
        else
        {
            // 非业务异常，记录异常日志
            _logger.LogError(context.Exception, "Api => {Path}{QueryString}", context.HttpContext.Request.Path, context.HttpContext.Request.QueryString);
        }

        context.Result = new JsonResult(result);
        context.ExceptionHandled = true;

        return Task.CompletedTask;
    }
}
